<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------
/**
 * Class Order
 * Desc  用户订单Model
 * Create on 2024/10/25 13:45
 * Create by wangyafang
 */

namespace app\api\model\wddj\usert;


use app\api\controller\wddj\usert\Map;
use app\api\model\wddj\Config;
use app\api\model\wddj\driver\CommissionRatio;
use app\api\model\wddj\trailer\CommissionRatio as CommissionRatioTrailer;
use app\api\model\wddj\usert\operation\StartingPrice;
use app\api\model\wddj\usert\operation\StartingPriceTrailer;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;

class Order extends Model
{
// 表名
    protected $name = 'wddj_order_trailer';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;


    protected static function init()
    {
        self::beforeInsert(function ($row) {
            if ($row['type'] == 1) {
                $row->departure_time = self::getDepartureTime();
            }
        });
    }

    /**
     * Desc 获取当前出发时间
     * Create on 2024/10/25 16:49
     * Create by wangyafang
     */
    public static function getDepartureTime()
    {
        $currentYear = date('Y');
        $currentMonth = date('m');
        $currentDay = date('d');
        $currentHour = date('H');
        $currentMinute = date('i');

// Determine the starting and ending minutes for the range
        if ($currentMinute < 10) {
            $startMinute = 0; // Start at 00
            $endMinute = 10;  // End at 10
        } elseif ($currentMinute < 20) {
            $startMinute = 10; // Start at 10
            $endMinute = 20;   // End at 20
        } elseif ($currentMinute < 30) {
            $startMinute = 20; // Start at 20
            $endMinute = 30;   // End at 30
        } elseif ($currentMinute < 40) {
            $startMinute = 30; // Start at 30
            $endMinute = 40;   // End at 40
        } elseif ($currentMinute < 50) {
            $startMinute = 40; // Start at 40
            $endMinute = 50;   // End at 50
        } else {
            $startMinute = 50; // Start at 50
            $endMinute = 59;    // End at 59
        }

// Format the output
        $output = sprintf('%04d-%02d-%02d %02d:%02d-%02d:%02d',
            $currentYear,
            $currentMonth,
            $currentDay,
            $currentHour,
            $startMinute,
            $currentHour,
            $endMinute
        );

        return $output;
    }


    /**
     * Desc 待接单详情数据
     * Create on 2024/11/1 14:18
     * Create by wangyafang
     */
    public static function acceptanceDetails($orderObj)
    {
        $paymentsObj = (new Payments())->where('order_id',$orderObj['id'])->find();
        if (empty($paymentsObj['pay_time'])) {
            $paymentsObj['pay_time'] = time();
        }
        $front = $paymentsObj['pay_time'] + 120;
        $front_time = date('H:i',$front);

        $behind = $paymentsObj['pay_time'] + 720;
        $behind_time = date('H:i',$behind);
        return $front_time.'-'.$behind_time;
    }

    /**
     * Desc 订单详情获取乘车人信息
     * Create on 2024/11/5 9:14
     * Create by wangyafang
     */
    public static function getPassenger($id)
    {
        $passengerObj = (new Passenger())->get($id);
        $data = array();
        if ($passengerObj) {
            $data = array(
                'name'=>$passengerObj['name'],
                'mobile'=>substr_replace($passengerObj['mobile'], '*****', 3, -3),
            );
        }

        return $data;

    }


    /**
     * Desc 预约检测自动创建订单
     * Create on 2025/05/22 17:30
     * Create by maomao
     */
    public static function autoCreate($param,$wechat_id)
    {
        $model = new self();
        $cityObj = (new \app\api\model\wddj\usert\operation\City())->where('city','like','%'.$param['city'].'%')->find();
        if (empty($cityObj)) {
            return '城市没有开通拖车服务';
        }
        $param['city_id'] = $cityObj['id'];

        //判断城市下的费用规则是否包含用户所选车辆类别
        $startingPrice = StartingPrice::where(['city_id'=>$param['city_id'],'vehicle_type'=>$param['city_type']])->where("FIND_IN_SET(:id,area_names)",['id'=>$param['to_city']])->find();
        if(empty($startingPrice))
            return '城市没有开通拖车服务';

//        $wechat_id = User::getWechatId($userid);
        $real_name_authentication_status = (new Config())->where('id',1)->value('real_name_authentication_status');
        if ($real_name_authentication_status == '1') {
            $where['wechat_id'] = array('eq',$wechat_id);
            $userRealNameAuthenticationObj = (new \app\api\model\wddj\usert\UserRealNameAuthentication())->where($where)->find();
            if (!$userRealNameAuthenticationObj) {
                return '请先到安全中心，进行实名认证';
            }
        }
        $awaitingPaymentOrderObj = $model->where('wechat_id',$wechat_id)->where('state','awaiting_payment')->find();
        if ($awaitingPaymentOrderObj) {
            return '有待补差订单未付款';
        }
        $out_trade_no = $order_no = wddj_create_order();
        $estimated_amount = $startingPrice['price'];
        $city_id = $param['city_id'];
        $from_lat = $param['from_lat'];//出发地纬度
        $from_lng = $param['from_lng'];
        $to_lat = $param['to_lat'];
        $to_lng = $param['to_lng'];
//        $estimated_amount = cache('city_id'.$city_id.'from_lat'.$from_lat.'from_lng'.$from_lng.'to_lat'.$to_lat.'to_lng'.$to_lng);
        $mapResult = (new Map())->get_driver_routes($param);
//        if (empty($estimated_amount)) {
//            $estimated_amount_result = \app\api\model\wddj\usert\operation\CostAllocation::estimated_amount($city_id,$mapResult['result']['routes'][0]['distance']);
//            $estimated_amount = $estimated_amount_result['estimated_amount'];
//        }
        $commissionRatioObj = (new CommissionRatio())->where('city_id',$city_id)->find();
        if (empty($commissionRatioObj)) {
            return '城市未配置抽成比例，无法下单';
        }
        $pay_amount = bcmul($estimated_amount,$param['driver_number'],2);
        $estimated_amount = bcmul($estimated_amount,$param['driver_number'],2);
        $create_data = array(
            'wechat_id'=>$wechat_id,
            'order_no'=>$order_no,
            'estimated_amount'=>$estimated_amount,
            'pay_amount'=>$pay_amount,
            'driving_distance'=>bcdiv($mapResult['result']['routes'][0]['distance'],1000,2),
            'driving_distance_meter'=>$mapResult['result']['routes'][0]['distance'],
            'travel_time'=>$mapResult['result']['routes'][0]['duration'],
            'end_time'=>strtotime("+{$mapResult['result']['routes'][0]['duration']} minutes {$param['departure_time']}"),
            'actual_meter'=>$mapResult['result']['routes'][0]['distance'],
            'actual_amount'=>$estimated_amount,
        );
        $create_data = array_merge($create_data,$param);
        if (!isset($param['remarks'])) {
            $create_data['remarks'] = '';
        }

        $paymentsModel = new Payments();
        Db::startTrans();
        try {
            $model->data($create_data);
            $model->allowField(true)->save();
            $payments_data = array(
                'order_id'=>$model->id,
                'out_trade_no'=>$out_trade_no,
                'pay_amount'=>$pay_amount,
                'payment_type'=>'prepaid',
                'payment_status'=>'unpaid',
            );
            $paymentsModel->data($payments_data);
            $paymentsModel->allowField(true)->save();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }

//        cache('city_id'.$city_id.'from_lat'.$from_lat.'from_lng'.$from_lng.'to_lat'.$to_lat.'to_lng'.$to_lng,NULL);

//        自动生成代价订单时无需生成支付信息，放在控制器中与检测费用一起支付
//        try {
//            $openid = wddj_get_openid($wechat_id);
//            $conf = Wxapp::unify('下单', $out_trade_no, $estimated_amount, $openid, request()->domain() . '/api/wddj/usert/order/notify');
//        } catch (\Exception $e) {
//            return $e->getMessage();
//        }
        return array(
            'id'=>$model->id,
            'estimated_amount'=>$estimated_amount,
            'out_trade_no'=>$out_trade_no
        );
    }

    /**
     * Desc 预约检测自动创建订单
     * Create on 2025/05/22 17:30
     * Create by maomao
     */
    public static function autoCreateTrailer($param,$wechat_id)
    {
        $model = new self();
        $cityObj = (new \app\api\model\wddj\usert\operation\CityTrailer())->where('city','like','%'.$param['city'].'%')->find();
        if (empty($cityObj)) {
            return '城市没有开通拖车服务';
        }
        $param['city_id'] = $cityObj['id'];

        //判断城市下的费用规则是否包含用户所选车辆类别
        $startingPrice = StartingPriceTrailer::where(['city_id'=>$param['city_id'],'vehicle_type'=>$param['city_type']])->where("FIND_IN_SET(:id,area_names)",['id'=>$param['to_city']])->find();
        if(empty($startingPrice))
            return '城市没有开通拖车服务';

//        $wechat_id = User::getWechatId($userid);
        $real_name_authentication_status = (new Config())->where('id',1)->value('real_name_authentication_status');
        if ($real_name_authentication_status == '1') {
            $where['wechat_id'] = array('eq',$wechat_id);
            $userRealNameAuthenticationObj = (new \app\api\model\wddj\usert\UserRealNameAuthentication())->where($where)->find();
            if (!$userRealNameAuthenticationObj) {
                return '请先到安全中心，进行实名认证';
            }
        }
        $awaitingPaymentOrderObj = $model->where('wechat_id',$wechat_id)->where('state','awaiting_payment')->find();
        if ($awaitingPaymentOrderObj) {
            return '有待补差订单未付款';
        }
        $out_trade_no = $order_no = wddj_create_order();
        $estimated_amount = $startingPrice['price'];
        $city_id = $param['city_id'];
        $from_lat = $param['from_lat'];//出发地纬度
        $from_lng = $param['from_lng'];
        $to_lat = $param['to_lat'];
        $to_lng = $param['to_lng'];
//        $estimated_amount = cache('city_id'.$city_id.'from_lat'.$from_lat.'from_lng'.$from_lng.'to_lat'.$to_lat.'to_lng'.$to_lng);
        $mapResult = (new Map())->get_driver_routes($param);
//        if (empty($estimated_amount)) {
//            $estimated_amount_result = \app\api\model\wddj\usert\operation\CostAllocation::estimated_amount($city_id,$mapResult['result']['routes'][0]['distance']);
//            $estimated_amount = $estimated_amount_result['estimated_amount'];
//        }
        $commissionRatioObj = (new CommissionRatioTrailer())->where('city_id',$city_id)->find();
        if (empty($commissionRatioObj)) {
            return '城市未配置抽成比例，无法下单';
        }
        $pay_amount = bcmul($estimated_amount,$param['driver_number'],2);
        $estimated_amount = bcmul($estimated_amount,$param['driver_number'],2);
        $create_data = array(
            'wechat_id'=>$wechat_id,
            'order_no'=>$order_no,
            'estimated_amount'=>$estimated_amount,
            'pay_amount'=>$pay_amount,
            'driving_distance'=>bcdiv($mapResult['result']['routes'][0]['distance'],1000,2),
            'driving_distance_meter'=>$mapResult['result']['routes'][0]['distance'],
            'travel_time'=>$mapResult['result']['routes'][0]['duration'],
            'end_time'=>strtotime("+{$mapResult['result']['routes'][0]['duration']} minutes {$param['departure_time']}"),
            'actual_meter'=>$mapResult['result']['routes'][0]['distance'],
            'actual_amount'=>$estimated_amount,
        );
        $create_data = array_merge($create_data,$param);
        if (!isset($param['remarks'])) {
            $create_data['remarks'] = '';
        }

        $paymentsModel = new PaymentsTrailer();
        Db::startTrans();
        try {
            $model->data($create_data);
            $model->allowField(true)->save();
            $payments_data = array(
                'order_id'=>$model->id,
                'out_trade_no'=>$out_trade_no,
                'pay_amount'=>$pay_amount,
                'payment_type'=>'prepaid',
                'payment_status'=>'unpaid',
            );
            $paymentsModel->data($payments_data);
            $paymentsModel->allowField(true)->save();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }

//        cache('city_id'.$city_id.'from_lat'.$from_lat.'from_lng'.$from_lng.'to_lat'.$to_lat.'to_lng'.$to_lng,NULL);

//        自动生成代价订单时无需生成支付信息，放在控制器中与检测费用一起支付
//        try {
//            $openid = wddj_get_openid($wechat_id);
//            $conf = Wxapp::unify('下单', $out_trade_no, $estimated_amount, $openid, request()->domain() . '/api/wddj/usert/order/notify');
//        } catch (\Exception $e) {
//            return $e->getMessage();
//        }
        return array(
            'id'=>$model->id,
            'estimated_amount'=>$estimated_amount,
            'out_trade_no'=>$out_trade_no
        );
    }
    
    /**
     * Desc 预约检测自动创建订单
     * Create on 2025/05/22 17:30
     * Create by maomao
     */
    public static function autoCreateNoTrailer($param,$wechat_id)
    {
        $model = new self();
        // $cityObj = (new \app\api\model\wddj\usert\operation\CityTrailer())->where('city','like','%'.$param['city'].'%')->find();
        // if (empty($cityObj)) {
        //     return '城市没有开通拖车服务';
        // }
        // $param['city_id'] = $cityObj['id'];

        //判断城市下的费用规则是否包含用户所选车辆类别
        // $startingPrice = StartingPriceTrailer::where(['city_id'=>$param['city_id'],'vehicle_type'=>$param['city_type']])->where("FIND_IN_SET(:id,area_names)",['id'=>$param['to_city']])->find();
        // if(empty($startingPrice))
        //     return '城市没有开通拖车服务';

//        $wechat_id = User::getWechatId($userid);
        $real_name_authentication_status = (new Config())->where('id',1)->value('real_name_authentication_status');
        if ($real_name_authentication_status == '1') {
            $where['wechat_id'] = array('eq',$wechat_id);
            $userRealNameAuthenticationObj = (new \app\api\model\wddj\usert\UserRealNameAuthentication())->where($where)->find();
            if (!$userRealNameAuthenticationObj) {
                return '请先到安全中心，进行实名认证';
            }
        }
        $awaitingPaymentOrderObj = $model->where('wechat_id',$wechat_id)->where('state','awaiting_payment')->find();
        if ($awaitingPaymentOrderObj) {
            return '有待补差订单未付款';
        }
        $out_trade_no = $order_no = wddj_create_order();
        // $estimated_amount = $startingPrice['price'];
        // $city_id = $param['city_id'];
        $from_lat = $param['from_lat'];//出发地纬度
        $from_lng = $param['from_lng'];
        $to_lat = $param['to_lat'];
        $to_lng = $param['to_lng'];
        $mapResult = (new Map())->get_driver_routes($param);
        // $commissionRatioObj = (new CommissionRatioTrailer())->where('city_id',$city_id)->find();
        // if (empty($commissionRatioObj)) {
        //     return '城市未配置抽成比例，无法下单';
        // }
        // $pay_amount = bcmul($estimated_amount,$param['driver_number'],2);
        // $estimated_amount = bcmul($estimated_amount,$param['driver_number'],2);
        $create_data = array(
            'wechat_id'=>$wechat_id,
            'order_no'=>$order_no,
            // 'estimated_amount'=>$estimated_amount,
            // 'pay_amount'=>$pay_amount,
            'estimated_amount'=>0,
            'pay_amount'=>0,
            'driving_distance'=>bcdiv($mapResult['result']['routes'][0]['distance'],1000,2),
            'driving_distance_meter'=>$mapResult['result']['routes'][0]['distance'],
            'travel_time'=>$mapResult['result']['routes'][0]['duration'],
            'end_time'=>strtotime("+{$mapResult['result']['routes'][0]['duration']} minutes {$param['departure_time']}"),
            'actual_meter'=>$mapResult['result']['routes'][0]['distance'],
            // 'actual_amount'=>$estimated_amount,
            'actual_amount'=>0,
        );
        $create_data = array_merge($create_data,$param);
        if (!isset($param['remarks'])) {
            $create_data['remarks'] = '';
        }

        $paymentsModel = new PaymentsTrailer();
        Db::startTrans();
        try {
            $model->data($create_data);
            $model->allowField(true)->save();
            $payments_data = array(
                'order_id'=>$model->id,
                'out_trade_no'=>$out_trade_no,
                // 'pay_amount'=>$pay_amount,
                'payment_type'=>'prepaid',
                'payment_status'=>'unpaid',
            );
            $paymentsModel->data($payments_data);
            $paymentsModel->allowField(true)->save();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }

        return array(
            'id'=>$model->id,
            // 'estimated_amount'=>$estimated_amount,
            'estimated_amount'=>0,
            'out_trade_no'=>$out_trade_no
        );
    }
}



 